﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CanDoo.Oil.WebApi.UnitTestProject
{
    public class ApiHelper
    {
        private HttpClient _httpClient;

        private string ServerBaseAddress;


        public ApiHelper()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(ServerBaseAddress);
        }

        public ApiHelper(string serverBaseAddress)
        {
            ServerBaseAddress = serverBaseAddress;
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(ServerBaseAddress);
        }

        /// <summary>
        /// string.Format("/api/customer/{0}", CardNo)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="url"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<TEntity> DoGet<TEntity>(string url,Dictionary<string,string> query) where TEntity:class
        {
            //var path = string.Format("/api/customer/{0}", CardNo);
            var path = url;
            if(!path.EndsWith("/"))
            {
                path += "/";
            }
            if(query.Count > 0)
                path += "?";
            foreach (var item in query)
            {
                path += item.Key + "=" + item.Value + "&";
            }
            if(path.EndsWith("&"))
            {
                path = path.Substring(0,path.Length -1);
            }
            var response = await _httpClient.GetAsync(path);
            if (response != null)
            {
                if (response.IsSuccessStatusCode)
                {
                    var responseValue = await response.Content.ReadAsStringAsync();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<TEntity>(responseValue);
                }
            }
            return await Task.FromResult<TEntity>(null);
        }

        /// <summary>
        /// string.Format("/api/customer/{0}", CardNo)
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="url"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<string> DoGet(string url, Dictionary<string, string> query)
        {
            //var path = string.Format("/api/customer/{0}", CardNo);
            var path = url;
            if (!path.EndsWith("/"))
            {
                path += "/";
            }
            if (query.Count > 0)
                path += "?";
            foreach (var item in query)
            {
                path += item.Key + "=" + item.Value + "&";
            }
            if (path.EndsWith("&"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            var response = await _httpClient.GetAsync(path);
            if (response != null)
            {
                if (response.IsSuccessStatusCode)
                {
                    var responseValue = await response.Content.ReadAsStringAsync();
                    return responseValue;
                }
            }
            return await Task.FromResult<string>(null);
        }

        public async Task<TResult> DoPost<TResult, TEntity>(string url,TEntity entity) 
            where TResult : class 
            where TEntity : class
        {
            //var url = "/api/customer";
            var strEncodeBody = JsonConvert.SerializeObject(entity);
            HttpContent content = new StringContent(strEncodeBody);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await _httpClient.PostAsync(url, content);
            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var resultValue = await response.Content.ReadAsStringAsync();

                    return Newtonsoft.Json.JsonConvert.DeserializeObject<TResult>(resultValue); ;
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var resultValue = await response.Content.ReadAsStringAsync();
                    try
                    {
                        return Newtonsoft.Json.JsonConvert.DeserializeObject<TResult>(resultValue);
                    }
                    catch (Exception ex)
                    {
                        //return new ApiResult(ApiResultType.error, "操作发生异常", null, ex.Message);
                    }
                }
            }

            return await Task.FromResult<TResult>(null);
        }

        public async Task<string> DoPost(string url, string entity)
        {
            //var url = "/api/customer";
            var strEncodeBody = entity;
            HttpContent content = new StringContent(strEncodeBody);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await _httpClient.PostAsync(url, content);
            if (response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var resultValue = await response.Content.ReadAsStringAsync();

                    return resultValue;
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var resultValue = await response.Content.ReadAsStringAsync();
                    try
                    {
                        return resultValue;
                    }
                    catch (Exception ex)
                    {
                        //return new ApiResult(ApiResultType.error, "操作发生异常", null, ex.Message);
                    }
                }
            }

            return await Task.FromResult<string>(null);
        }
    }
}
